package com.lunm.im.server.handler;

import com.lunm.im.factory.ServicesFactory;
import com.lunm.im.massage.RpcRequestMessage;
import com.lunm.im.massage.RpcResponseMessage;
import com.lunm.im.server.service.HelloService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @version 1.0.0
 * @Author shawn
 * @Date 2024/12/31 9:04
 */
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage response = new RpcResponseMessage();
        response.setSequenceId(msg.getSequenceId());
        try {
            // 获取真正的实现对象
            HelloService service = (HelloService) ServicesFactory.getService(Class.forName(msg.getInterfaceName()));

            // 获取要调用的方法
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterTypes());

            // 调用方法
            Object invoke = method.invoke(service, msg.getParameterValue());
            // 调用成功
            response.setReturnValue(invoke);
        } catch (Exception e) {
            e.printStackTrace();
            // 调用异常
            response.setExceptionValue(e);
        }
        // 返回结果
        ctx.writeAndFlush(response);
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        RpcRequestMessage message = new RpcRequestMessage(1, "com.lunm.im.server.service.HelloService", "sayHello", String.class, new Class[]{String.class}, new Object[]{"张三"});
        HelloService service = (HelloService) ServicesFactory.getService(Class.forName(message.getInterfaceName()));
        Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
        Object invoke = method.invoke(service, message.getParameterValue());
        System.out.println(invoke);
    }
}
